package com.sh.pangea.dsa.ui.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sh.lib.appbase.impl.NetBaseAppManager;
import com.sh.lib.base.bean.SoftWare;
import com.sh.lib.base.callback.UpGradeListener;
import com.sh.lib.bossstat.impl.BossStatManager;
import com.sh.lib.dsa.bean.UserInfo;
import com.sh.lib.dsa.callback.LoginListener;
import com.sh.lib.dsa.impl.AnalyzeManager;
import com.sh.pangea.dsa.R;
import com.sh.pangea.dsa.Utils.AppManager;
import com.sh.pangea.dsa.Utils.DesUtils;
import com.sh.pangea.dsa.Utils.GatherUtils;
import com.sh.pangea.dsa.Utils.OnCustomDialogListener;
import com.sh.pangea.dsa.Utils.PreferenceUtil;
import com.sh.pangea.dsa.Utils.SettingConfig;
import com.sh.pangea.dsa.constant.InitConfig;
import com.sh.pangea.dsa.view.RoundedImageView;
import com.sh.pangea.dsa.view.WelcomeView;
import com.sh.pangea.dsa.view.widget.AlertDialogFactory;
import com.skyworth_hightong.bean.AppUpDateInfo;
import com.skyworth_hightong.update.constant.UpGradeConstant;
import com.skyworth_hightong.update.logic.StorageUtils;
import com.skyworth_hightong.update.server.DownLoadManager;

import java.io.File;
import java.util.List;



/**
 * Created by sam on 2016/9/28.
 */

public class WelcomeActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String VIDEO_NAME = "welcome_video.mp4";

    private InputType inputType = InputType.NONE;

    private LinearLayout ll_button;

    private Button buttonLeft, buttonRight;

    private WelcomeView welcomeView;

    private ViewGroup contianer;

    private TextView appName;

    private PreferenceUtil mPreferenceUtil;

    private DesUtils des = null;

    //登录状态 -1：未登录；0：登录成功；1：登录失败
    private int loginStatus = -1;
    //是否需要升级 -1：不需要升级； 1： 需要升级
    private int updataStatus = -1;

    public static UserInfo userInfo = null;

    private RoundedImageView view;

    private Bitmap bitmap;

    //哪几个不需要圆角
    private int corners = 0;

    //圆角弧度的像素
    private int radius = 15;

    private Context mContext;

    private static final String admin = "admin";

    /**
     * 版本检测用到的变量
     */
    private boolean isForceUpdate;
    private String cancelSoftWareInfo = null;
    private NetBaseAppManager mNetBaseAppManager;
    private AlertDialogFactory mAlertDialogFactory;
    private DownLoadManager mDownLoadManager;
    private SoftWare mSoftWare;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        AppManager.getAppManager().addActivity(WelcomeActivity.this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        setContentView(R.layout.activity_welcome);
        if(mNetBaseAppManager == null ){
            mNetBaseAppManager = NetBaseAppManager.getInstance(mContext);
        }
        if (mPreferenceUtil == null) {
            mPreferenceUtil = PreferenceUtil.getInstance(this);
        }
        if (null == mAlertDialogFactory) {
            mAlertDialogFactory = AlertDialogFactory.getInstance();
        }
        if (null == mDownLoadManager) {
            mDownLoadManager = DownLoadManager.getInstance(mContext);
        }
        if (des == null) {
            des = new DesUtils("skyworth");//自定义密钥
        }
        initPortal();

        findView();

        initView();


    }

    private void initPortal() {
        AnalyzeManager.instence().setPortalAddress("http://106.2.186.52:8081/sh-dsa/a");
        BossStatManager.instence().setPortalAddress("http://60.205.14.72:9595/bossstat");
        NetBaseAppManager.getInstance(mContext).initPortal("http://60.205.14.72:9090/appbase",
                InitConfig.terminalType, InitConfig.portalRegionid);
        checkVersion(true);
    }


    private void findView() {
        ll_button = (LinearLayout) findViewById(R.id.ll_button);
        buttonLeft = (Button) findViewById(R.id.buttonLeft);
        buttonRight = (Button) findViewById(R.id.buttonRight);
        contianer = (ViewGroup) findViewById(R.id.container);
        welcomeView = (WelcomeView) findViewById(R.id.formView);
        appName = (TextView) findViewById(R.id.appName);
        view = (RoundedImageView) findViewById(R.id.imageView2);
        welcomeView.post(new Runnable() {
            @Override
            public void run() {
                int delta = welcomeView.getTop() + welcomeView.getHeight();
                welcomeView.setTranslationY(-1 * delta);
            }
        });
    }

    private void initView() {

        buttonRight.setOnClickListener(this);
        buttonLeft.setOnClickListener(this);
    }

    /**
     * 播放动画
     */
    private void playAnim() {
        ObjectAnimator anim = ObjectAnimator.ofFloat(appName, "alpha", 0, 1);
        anim.setDuration(3000);
        anim.setRepeatCount(1);
        anim.setRepeatMode(ObjectAnimator.REVERSE);
        anim.start();
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                Log.i("状态","升级状态： " + updataStatus +"   登录状态： "+ loginStatus);
                if (updataStatus == -1){
                    appName.setVisibility(View.INVISIBLE);
                    AnalyzeManager.instence().cancelAll();
                    NetBaseAppManager.getInstance(mContext).cancelAll();
                    if (loginStatus == 0) {
                        goMainActivity();
                    } else {
                        welcomeView.animate().translationY(0).alpha(1).setDuration(500).start();
                        inputType = InputType.LOGIN;
                        buttonLeft.setText(R.string.button_confirm_login);
                        buttonRight.setText(R.string.button_return);
                        buttonLeft.setVisibility(View.VISIBLE);
                        buttonRight.setVisibility(View.VISIBLE);
                    }
                }else if (updataStatus  == 1){
                    String updateMsg = null;
                    String updateOk = null;
                    String updateCancel = null;
                    Resources res = mContext.getResources();
                    isForceUpdate = SettingConfig.isForceUpdate(
                            mContext, mSoftWare);
                    Log.i("版本检测","是否强制更新  ：  "+ isForceUpdate);
                    if (isForceUpdate) {
                        PreferenceUtil.getInstance(
                                WelcomeActivity.this).saveInt(
                                "isForceUpdate", 1);
                        updateMsg = res
                                .getString(R.string.update_force_msg);
                        updateOk = res
                                .getString(R.string.update_force_ok);
                        updateCancel = res
                                .getString(R.string.update_force_cancel);
                        if (!isFinishing()) {
                            showAlertDialog(mSoftWare, updateMsg,
                                    updateCancel, updateOk, false);
                        }
                    } else {
                        PreferenceUtil.getInstance(
                                WelcomeActivity.this).saveInt(
                                "isForceUpdate", 0);
                        // 普通升级逻辑
                        String updateMsgStart = res
                                .getString(R.string.update_msg_start);
                        updateOk = res
                                .getString(R.string.update_ok);
                        updateCancel = res
                                .getString(R.string.update_cancel);
                        updateMsg = updateMsgStart
                                + mSoftWare.getVersionName();
                        if (!isFinishing()) {
                            showAlertDialog(mSoftWare, updateMsg,
                                    updateCancel, updateOk, false);
                        }
                    }

                }

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        autoLogin();
        playAnim();
        if (view != null) {
            BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.mipmap.ic_launcher);
            bitmap = bd.getBitmap();
            try {
                view.setImage(bitmap, radius, corners);
            } catch (Exception e) {

            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * UserInfo的get,set方法，方便后续要用
     *
     * @return
     */
    public static UserInfo getUserInfo() {
        return userInfo;
    }

    public void setUserInfo(UserInfo userInfo) {
        this.userInfo = userInfo;
    }

    @Override
    public void onClick(View view) {
        final int delta = welcomeView.getTop() + welcomeView.getHeight();
//        String userName = "";
//        String passWord = "";
        switch (inputType) {
            case NONE:
                if (view == buttonLeft) {
                    welcomeView.animate().translationY(0).alpha(1).setDuration(500).start();
                    inputType = InputType.LOGIN;
                    buttonLeft.setText(R.string.button_confirm_login);
                    buttonRight.setText(R.string.button_return);
                } else if (view == buttonRight) {

                    //TODO 可以添加确认退出的对话框
                    finish();
                }
                break;
            case LOGIN:
                final String userName_login = welcomeView.getUserName();
                final String passWord_login = welcomeView.getPassWord();
                if (view == buttonLeft) {
                    Log.i("CGZ", "登录状态，点了左键");
                    if (userName_login == null || "".equals(userName_login) ||
                            passWord_login == null || "".equals(passWord_login)) {
                        Toast.makeText(WelcomeActivity.this, "用户名或密码不能为空~", Toast.LENGTH_SHORT).show();
                    } else {

                        if (userName_login.equals(admin) && passWord_login.equals(admin)){
                            UserInfo mUserInfo = new UserInfo();
                            mUserInfo.setLoginName(admin);
                            mUserInfo.setName(admin);
                            loginSuccess(mUserInfo,delta,admin,admin);
                        }else{

                            AnalyzeManager.instence().login(InitConfig.CON_TIME_OUT, InitConfig.SO_TIME_OUT, userName_login, passWord_login,
                                    new LoginListener() {
                                        @Override
                                        public void onSuccess(UserInfo userInfo) {
                                            loginSuccess(userInfo,delta,"userName_login","passWord_login");
                                        }

                                        @Override
                                        public void onPrepare(String s) {

                                        }

                                        @Override
                                        public void onFail(int i, String s) {
                                            Log.i("CGZ", "登录失败，请重试   :   " + i + "      ,     " + s);
                                            showToast(WelcomeActivity.this, "用户名或密码有误，请重试!");
                                        }
                                    });

                        }
                    }

                } else if (view == buttonRight) {
                    welcomeView.animate().translationY(-1 * delta).alpha(0).setDuration(500).start();
                    Log.i("CGZ", "登录状态，点了右键");
                    inputType = InputType.NONE;
                    buttonLeft.setText(R.string.button_login);
                    buttonRight.setText(R.string.button_signout);
                }
                break;
            case SIGN_UP:
                String userName_sign = welcomeView.getUserName();
                String passWord_sign = welcomeView.getPassWord();
                if (view == buttonLeft) {
                    Log.i("CGZ", "注册状态，点了右键");
                    if (userName_sign == null || "".equals(userName_sign) ||
                            passWord_sign == null || "".equals(passWord_sign)) {
                        Toast.makeText(WelcomeActivity.this, "用户名或密码不能为空~", Toast.LENGTH_SHORT).show();
                    } else {
                        welcomeView.animate().translationY(-1 * delta).alpha(0).setDuration(500).start();
                        goMainActivity();
                    }
                } else if (view == buttonRight) {
                    welcomeView.animate().translationY(-1 * delta).alpha(0).setDuration(500).start();
                    Log.i("CGZ", "注册状态，点了右键");
                    buttonLeft.setText(R.string.button_login);
                    buttonRight.setText(R.string.button_signout);
                    inputType = InputType.NONE;
                }
                break;
        }
    }

    enum InputType {
        NONE, LOGIN, SIGN_UP;
    }

    /**
     * 去主页
     */
    private void goMainActivity() {
        Log.i("状态","升级状态： " + updataStatus +"   登录状态： "+ loginStatus);
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    /**
     * 弹吐司
     *
     * @param context
     * @param msg
     */
    public void showToast(final Activity context, final String msg) {
        if ("main".equals(Thread.currentThread().getName())) {
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
        } else {
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void loginSuccess(UserInfo mUserInfo,int delta,String userName,String passWord) {
        cancleLogin(WelcomeActivity.this, delta);
        Log.i("CGZ", mUserInfo.toString());
        setUserInfo(mUserInfo);
        goMainActivity();
        try {
            mPreferenceUtil.saveString("userName", des.encrypt(userName));
            mPreferenceUtil.saveString("passWord", des.encrypt(passWord));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 在登录界面点返回后，让输入用户名和密码的界面消失
     *
     * @param context
     * @param delta
     */
    public void cancleLogin(final Activity context, final int delta) {
        if ("main".equals(Thread.currentThread().getName())) {
            welcomeView.animate().translationY(-1 * delta).alpha(0).setDuration(500).start();
        } else {
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    welcomeView.animate().translationY(-1 * delta).alpha(0).setDuration(500).start();
                }
            });
        }
    }

    /**
     * 是否自动登录
     *
     * @return
     */
    private boolean autoLogin() {
        String userName = null;
        String passWord = null;
        try {
            Log.i("CGZ", mPreferenceUtil.getString("userName", "") + "  加密中  " + mPreferenceUtil.getString("passWord", ""));
            userName = des.decrypt(mPreferenceUtil.getString("userName", ""));
            passWord = des.decrypt(mPreferenceUtil.getString("passWord", ""));
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (userName == null || "".equals(userName) ||
                passWord == null || "".equals(passWord)) {
            return false;
        } else {
            Log.i("CGZ", userName + " 解密后 " + passWord);
            login(userName, passWord);
            return true;
        }
    }

    /**
     * 自动登录的接口
     *
     * @param userName
     * @param passWord
     */
    private void login(final String userName, final String passWord) {
        AnalyzeManager.instence().login(InitConfig.CON_TIME_OUT, InitConfig.SO_TIME_OUT, userName, passWord,
                new LoginListener() {
                    @Override
                    public void onSuccess(UserInfo userInfo) {
                        loginStatus = 0;
                        Log.i("CGZ", userInfo.toString());
                        setUserInfo(userInfo);
                        try {
                            Log.i("CGZ", userName + " 加密前 " + passWord);
                            mPreferenceUtil.saveString("userName", des.encrypt(userName));
                            mPreferenceUtil.saveString("passWord", des.encrypt(passWord));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onPrepare(String s) {

                    }

                    @Override
                    public void onFail(int i, String s) {
                        loginStatus = 1;
                        if (!autoLogin()){
                            Log.i("CGZ", "登录失败，请重试   :   " + i + "      ,     " + s);
                            showToast(WelcomeActivity.this, "用户名或密码有误，请重试!");
                        }

                    }
                });
    }

    /**
     * 检测新版是否跟新
     *
     * @param isShow true 需要进度提示，并且弹框升级 false 不需要提示
     */
    private void checkVersion(final boolean isShow) {
        String deviceId = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
        newGetSoftWareInfo(deviceId);
    }

    /**
     * 获取应用升级信息
     */
    private void newGetSoftWareInfo(String deviceId) {
        Log.i("版本检测","测试3 : ");
        String pkName = mContext.getPackageName();
        String versionName = "";
        int versionCode = 0;
        try {
            versionName = mContext.getPackageManager().getPackageInfo(
                    pkName, 0).versionName;
            versionCode = mContext.getPackageManager().getPackageInfo(
                    pkName, 0).versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.i("版本检测","版本信息 ：　versionName:"+versionName+"   versionCode:"+versionCode);
        mNetBaseAppManager.getSoftWareInfo(mContext.getPackageName(), deviceId,
                versionCode+"", versionName, InitConfig.CON_TIME_OUT, InitConfig.SO_TIME_OUT,
                new UpGradeListener() {
                    @Override
                    public void onSuccess(List<SoftWare> list) {
                        cancelSoftWareInfo = null;
                        mSoftWare = SettingConfig.isNeedUpdate(
                                mContext, list);
                        Log.i("版本检测",list.toString());
                        if (mSoftWare != null) {
                            updataStatus = 1;//APK需要升级
                        } else {
                            updataStatus = -1;
                            //虽然有升级文件，但本应用不需要升级
//                            userStateManager.autoLogin();
                            Log.i("版本检测","版本信息为空");
                        }
                    }

                    @Override
                    public void onPrepare(String s) {
                        Log.i("","版本检测 onPrepare");
                        if (cancelSoftWareInfo != null) {
                            mNetBaseAppManager.cancelReq(cancelSoftWareInfo);
                        }
                        cancelSoftWareInfo = s;
                    }

                    @Override
                    public void onException(Exception e) {
                        Log.i("","版本检测 onExection");
                        Log.e("",e.getLocalizedMessage());
//                        userStateManager.autoLogin();
                        cancelSoftWareInfo = null;
                        updataStatus = -1;
                    }

                    @Override
                    public void onFail(int i) {
                        updataStatus = -1;
                        Log.i("","版本检测 onFail :  "+ i);
                        Log.w("","retCode" + i);
//                        userStateManager.autoLogin();
                        cancelSoftWareInfo = null;
                    }
                });
    }

    protected void showAlertDialog(final SoftWare software, String msg,
                                   final String cancel, final String confim,
                                   final boolean isSingleButton) {
        mAlertDialogFactory.createAlertDialog(mContext, msg, cancel, confim,
                isSingleButton, new OnCustomDialogListener() {

                    @Override
                    public void confirm() {
                        AppUpDateInfo updateInfo = new AppUpDateInfo();
                        updateInfo.setAppVersion(software.getVersionCode());
                        updateInfo.setPackageName(software.getPackageName());
                        updateInfo.setAppVersionName(software.getVersionName());
                        updateInfo.setDownloadAddr(software.getDownloadLink());
                        String flag = software.getForceUpgradeVersion();
                        GatherUtils.getInstance(mContext).gatherAppUpgrade(software.getVersionName());
                        updateInfo.setForceUpdateFlag(flag);
                        if (mDownLoadManager.isDownLoaded(updateInfo)) {
                            // TODO 回头下载方法需要提供接口
                            String filePath = StorageUtils.getCacheDirectory(
                                    mContext).getAbsolutePath();
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(
                                    Uri.fromFile(new File(filePath, updateInfo
                                            .getPackageName()
                                            + UpGradeConstant.APP_EXPANDED_NAME)),
                                    "application/vnd.android.package-archive");
                            startActivity(intent);
                        } else {
                            Intent intent = new Intent(
                                    WelcomeActivity.this,
                                    UpgradeActivity.class);
                            intent.putExtra("software", software);
                            startActivity(intent);
                        }
                    }

                    @Override
                    public void cancel() {
                        if ("退出".equals(cancel)) {
                            AppManager.getAppManager().AppExit(mContext);
                        } else if ("取消".equals(cancel)) {
                            if (loginStatus == 0) {
                                goMainActivity();
                            } else {
                                buttonLeft.setVisibility(View.VISIBLE);
                                buttonRight.setVisibility(View.VISIBLE);
                            }
                        }

                    }
                }).show();
    }



}
